package com.yjh.server.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjh.common.other.BusinessException;
import com.yjh.common.utils.JwtUtil;
import com.yjh.pojo.dto.UpdatePswDto;
import com.yjh.pojo.entity.User;
import com.yjh.pojo.vo.R;
import com.yjh.pojo.vo.UserVo;
import com.yjh.server.mapper.UserMapper;
import com.yjh.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;


    public UserVo login(User user){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,user.getUsername());
        User dbUser = userMapper.selectOne(wrapper); // 数据库查询交给DAO层
        if (dbUser == null) {
            throw new BusinessException("用户名不存在"); // 抛出自定义异常
        }

        // 2. 校验密码（MD5加密后比对）
        String inputPasswordMd5 = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        if (!inputPasswordMd5.equals(dbUser.getPassword())) {
            throw new BusinessException("密码错误");
        }

        // 3. 是管理员但身份不匹配
        if(user.getRole()!=0&&!dbUser.getRole().equals(user.getRole())){
//            if (!dbUser.getRole().equals(user.getRole())) {
                throw new BusinessException("不存在该管理员");
//            }
        }


        // 4. 生成JWT令牌
        String token = JwtUtil.generateToken(dbUser.getUsername(), dbUser.getUserId().toString());

        // 5. 封装返回结果（UserVo）
        UserVo userVo = new UserVo();
        userVo.setUserId(dbUser.getUserId());
        userVo.setToken(token);

        return userVo;
    }

    @Override
    public void updatePsw(UpdatePswDto updatePswDTO,String userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        // 验证原密码 - 直接使用MD5
        String encryptedOldPassword = DigestUtils.md5DigestAsHex(updatePswDTO.getOldPassword().getBytes());
        if (!encryptedOldPassword.equals(user.getPassword())) {
            throw new BusinessException("原密码错误");
        }

        // 更新密码 - 直接使用MD5
        String encryptedNewPassword = DigestUtils.md5DigestAsHex(updatePswDTO.getNewPassword().getBytes());
        user.setPassword(encryptedNewPassword);
        userMapper.updateById(user);

//        return R.success("密码修改成功");

    }
}
